package com.example.image.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * 自定义Glide模块
 */
class CustomGlideModule: AppGlideModule(){

    /**
     * 自动以Glide内存和磁盘
     */

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //计算使用多大的内存空间
       val glidemorySize=MemorySizeCalculator.Builder(context).build().memoryCacheSize/6L

        //设置内存大小(默认为当前App内存的1/8)
        builder.setMemoryCache(LruResourceCache(glidemorySize))

        //设置磁盘大小
        builder.setDiskCache(InternalCacheDiskCacheFactory(context,"glide_cache",300*1024*1024))
    }

    /**
     * 自定义网络缓存大小
     * Glide网络采用OkHttp实现
     */
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {

        try {
            val bulide=OkHttpClient.Builder()
            //先考虑外部SDK,如果没有再考虑内部SDK
            val externalDir= Environment.getExternalStorageDirectory()
            var cacheDir= if( externalDir.exists()){
                "${externalDir.absolutePath}/glideCache"//外置SD卡
            }else{
                "${context.externalCacheDir?.absolutePath}/glideCache" //内置SD卡
            }

            //创建一个文件
            val cachFile=File(cacheDir)
            //计算缓存大小
            var casheSize=50*1024*1024L
            if(externalDir.exists() && externalDir.totalSpace>0L){
                casheSize=externalDir.totalSpace/8L
            }else{
                context.externalCacheDir?.totalSpace?.div(8L)?:10 * 1024 *1024
            }


            val newworkCache=Cache(cachFile,2000L)

            //设置网络缓存目录
            bulide.cache(newworkCache)


            val newOkHttpClient=bulide.build()
            //替换OkHttp为客户端
            registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(newOkHttpClient))
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
}